<?php
	/**
	 *	Copyright (c) TeamFlamingo And gray 2004-2009
	 *	www.me-live.com.cn / www.i-gray.cn
	 *
	 *	[ WARNING ]
	 *		This is NOT a freeware!
	 *		You MUST get author's authorization before using it!
	 *	[ WARNING ]
	 *
	 *	Name : tree.lib.php / Development Code Evolve
	 *	Created / Modify : 2010-3-25 / --
	 */

	if( !defined( 'IN_TEAME' ) )
	{
		exit( 'Access Denied' );
	}

	class	Tree
	{
		private	$arr		=	array();
		private	$clear		=	array();

		private	$trees		=	array();
		private	$second		=	array();
		private	$third		=	array();

		public	function	__construct( $arr )
		{
			$this->arr	=	$arr;
			$key	=	$tempArr	=	null;

			foreach( $this->arr as $key => $tempArr )
			{
				if( $tempArr )
					if( $tempArr['thirdParentId'] != '0' )
						$this->reBuildArr( $tempArr, $tempArr['thirdParentId'] );
					elseif( $tempArr['secondParentId'] != '0' )
						$this->reBuildArr( $tempArr, $tempArr['secondParentId'] );
					elseif( $tempArr['firstParentId'] != '0' )
						$this->reBuildArr( $tempArr, $tempArr['firstParentId'] );
					else
						$this->reBuildArr( $tempArr );
			}

			$this->addChild();
		}

		private	function	addChild()
		{
			foreach( $this->clear as $tempArr )
			{
				if( $tempArr['pid'] != '0' )
					$this->clear[$tempArr['pid']]['child']	=	true;
			}
		}

		private	function	reBuildArr( $arr, $key = false )
		{
			$pid	=	$key ? $key : '0';
			$this->clear[$arr['fid']]	=	array( 'pid' => $pid, 'fid' => $arr['fid'], 'forumName' => $arr['forumName'], 'child' => false );
		}

		private	function	clearArr ( $arr )
		{
			unset( $arr['firstParentId'], $arr['secondParentId'], $arr['thirdParentId'], $arr['child'] );
			return	$arr;
		}

		public	function	parse ()
		{
			global	$MDK;
			usort( $this->clear, "Tree::fix" );
			foreach( $this->clear as $key => $value )
			{
				$oImg	=	$value['child'] ? '<img src="./images/more.png" id="forums_child_' . $value['fid'] . '" />' : '';
				$oSty	=	$value['pid'] != '0' ? 'none;' : 'block';
				$oColor	=	isset( $MDK['f'] ) && $MDK['f'] == $value['fid'] ? '#92be04' : '#fff';
				$oDiv	=	'<div id="forums_parent_' . $value['pid'] . '" style="display:' . $oSty . ';background-color:' . $oColor . '"><a href="./?f=' . $value['fid'] . '">' . $value['forumName'] . '</a>' . $oImg . '</div>';
				$this->trees[]	=	$oDiv;
			}
			//print_r( $this->clear );
			return	$this->trees;
		}

		//	[CH]	按照板块ID顺序排列数组
		static	function fix( $a, $b )
		{
			if( $a['pid'] == '0' && $b['pid'] == '0' )
				return	$a['fid'] > $b['fid'] ? 1 : -1;

			if( $a['pid'] == '0' && $b['pid'] != '0' )
				return	$a['fid'] > $b['pid'] ? 1 : $a['fid'] == $b['pid'] ? 1 : -1;

			if( $a['pid'] != '0' && $b['pid'] == '0' )
				return	$a['pid'] > $b['fid'] ? 1 : $a['pid'] == $b['fid'] ? 1 : -1;

			return	( $a['fid'] < $b['fid'] ) ? -1 : 1;
		}
	}
?>